package com.hbnu.system.controller;

import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/cas")
public class CasLoginController {

    @Autowired
    private IUserService userService;

    @Value("${front.url}")
    private String frontUrl;

    /**
     * CAS登录回调处理
     */
    @GetMapping("/login")
    public String casLogin(HttpServletRequest request) {
        // 从CAS认证后的请求中获取用户名
        String username = request.getRemoteUser();

        try {
            // 根据用户名查询用户信息
            User user = userService.getUserByAccount(username);
            if (user == null) {
                // 用户不存在，重定向到错误页面
                return "redirect:" + frontUrl + "/login?error=user_not_found";
            }

            // 使用现有getJwtToken方法生成令牌
            String token = JwtUtils.getJwtToken(user.getUid(), user.getRole());

            // 将令牌存储到session和用户对象
            HttpSession session = request.getSession();
            session.setAttribute("token", token);
            session.setAttribute("user", user);

            // 重定向到前端首页，并带上token
            return "redirect:" + frontUrl + "?token=" + token;
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:" + frontUrl + "/login?error=system_error";
        }
    }

    /**
     * 登出处理
     */
    @GetMapping("/logout")
    public String casLogout(HttpServletRequest request) {
        // 使session失效
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate();
        }
        // 重定向到CAS登出页面
        return "redirect:https://authserver.hbnu.edu.cn/authserver/logout?service=" + frontUrl;
    }
}